package com.test

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional

@Transactional(readOnly = true)
class UserController {
	def login = {}
	
	def beforeInterceptor = [action:this.&auth, except:['login','logout','authenticate']]
	
	/**
	 * 形如logout 这样的闭包会在URL中暴露给最终用户
	 * debug()这样的方法是私有的，只能被类中的其他闭包或方法调用
	 * 可以通过末尾的括号来判断debug()是一个方法...
	 */
	def debug(){   
		println "DEBUG:${actionUri} called."
		println "DEBUG:${params}"
	}
	
	def auth = {
		if(!session.user){
			redirect(action:"login")
			return false
		}
		
		if(!session.user.isAdmin){
			flash.message = "Tsk tsk-admins only"
			redirect(controller:"race", action:"index")
			return false
		}
	}
	
	def logout = {
		flash.message = "Goodbye, ${session.user.login}! "
		session.user = null
		redirect(action:"login")
	}
	
	def authenticate = {
		def user = User.findByLoginAndPassword(params.login, params.password)
		if(user){
			session.user = user
			flash.message = "Hello, ${user.login}! "
			redirect(controller:"race")
		}else{
			flash.message = "Sorry, ${params.login}. Please try again."
			redirect(action:"login")
		}
	}
	
	
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
/**
    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond User.list(params), model:[userInstanceCount: User.count()]
    }*/
	
	def index = {
		redirect(action:"list", params:params)
	}
	/***
	 * Action 闭包一般以3 种方式结束(三个R：)
	 * 第一个R——redirect
	 * 第二个R——render
	 * 最后的R——return
	 */
	def list = {
		params.max = Math.min(params.max?params.int('max'): 10, 100)
		[userInstanceList: User.list(params), userInstanceTotal:User.count()]	//return是隐含
	}
/**	
	def create () {
		respond new User(params)
	}*/
	
	def create = {
		def userInstance = new User();
		userInstance.properties = params
		return [userInstance:userInstance]
	}
/**	
    def show(User userInstance) {
        respond userInstance
    }*/
	
	def show = {
		def userInstance = User.get(params.id)
		if(!userInstance){
			flash.message = "${message(code:'default.not.found.message', args:[message(code:'user.label', defualt:'User'), params.id])}"
			redirect(action:"list")
		}else{
			[userInstance:userInstance]
		}
		
	}
/**
    @Transactional
    def save(User userInstance) {
        if (userInstance == null) {
            notFound()
            return
        }

        if (userInstance.hasErrors()) {
            respond userInstance.errors, view:'create'
            return
        }

        userInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
                redirect userInstance
            }
            '*' { respond userInstance, [status: CREATED] }
        }
    }*/
	
	/**	----------message传参原理----------
	 * 	default.created.message={0} {1} created
	 *	default.updated.message={0} {1} updated
	 *	default.deleted.message={0} {1} deleted
	 */
	def save = {
		def userInstance = new User(params)
		if(userInstance.save(flush:true)){
			flash.message = message(code:'default.created.message', args:[message(code:'user.label', default:'User'), userInstance.id])
			redirect(action:"show", id:userInstance.id)
		}else{
			render(view:"create", model:[userInstance:userInstance])
		}
	}

    def edit(User userInstance) {
        respond userInstance
    }

    @Transactional
    def update(User userInstance) {
        if (userInstance == null) {
            notFound()
            return
        }

        if (userInstance.hasErrors()) {
            respond userInstance.errors, view:'edit'
            return
        }

        userInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'User.label', default: 'User'), userInstance.id])
                redirect userInstance
            }
            '*'{ respond userInstance, [status: OK] }
        }
    }

    @Transactional
    def delete(User userInstance) {

        if (userInstance == null) {
            notFound()
            return
        }

        userInstance.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'User.label', default: 'User'), userInstance.id])
                redirect action:"list", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {   
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
                redirect action: "list", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }
}
